package com.newhopegroup.webcommons.jsJsonCrossCall;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wangshida on 15/7/8.
 * JS使用JSON跨域调用
 * xmlns:mvc="http://www.springframework.org/schema/mvc"
 * <p/>
 * http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 * <p/>
 * <mvc:annotation-driven/>
 * <mvc:interceptors>
 * <bean class="com.newhopegroup.webcommons.jsJsonCrossCall.JsonCrossCallForJSInterceptor"/>
 * </mvc:interceptors>
 */
public class JsonCrossCallForJSInterceptor extends HandlerInterceptorAdapter {

//    GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

    private static final Logger logger = LoggerFactory.getLogger(JsonCrossCallForJSInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getMethod() == "POST" || request.getMethod() == "GET") {
            response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
//            response.setHeader("Access-Control-Max-Age", "60"); // seconds to cache preflight request --> less OPTIONS traffic
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        return super.preHandle(request, response, handler);
    }
}
